﻿#pragma once

#include <string>
#include <Windows.h>

/**
 * WMI查询的进程信息
 */
class process_query_info
{
public:
    /**
     * @brief 构造process_query_info对象
     *
     * @param process_id 进程id
     * @param process_name 进程名称
     * @param process_cmd_line 进程命令行
     */
    process_query_info(DWORD process_id,
        const std::wstring& process_name,
        const std::wstring& process_cmd_line)
        : id(process_id)
        , name(process_name)
        , cmd_line(process_cmd_line)
    {
        init_start_time();
    }

    DWORD get_id() const
    {
        return id;
    }

    const std::wstring& get_name() const
    {
        return name;
    }

    const std::wstring& get_cmd_line() const
    {
        return cmd_line;
    }

    /**
     * @brief 获取进程的启动时间，以yyyy-MM-dd HH:mm:ss格式表示
     *
     * @return 进程启动时间
     */
    std::wstring get_start_time() const
    {
        FILETIME local_file_time = { 0 };
        FileTimeToLocalFileTime(&start_time, &local_file_time);
        SYSTEMTIME sys_time = { 0 };
        FileTimeToSystemTime(&local_file_time, &sys_time);
        WCHAR buff[32] = { 0 };
        wsprintf(buff,
            L"%4d-%02d-%02d %02d:%02d:%02d",
            sys_time.wYear,
            sys_time.wMonth,
            sys_time.wDay,
            sys_time.wHour,
            sys_time.wMinute,
            sys_time.wSecond);
        return std::wstring(buff);
    }

private:
    /**
     * @brief 获取进程启动时间
     */
    void init_start_time()
    {
        FILETIME not_use;
        // GetProcessTimes需要PROCESS_QUERY_INFORMATION权限
        HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, id);
        if (process != nullptr)
        {
            GetProcessTimes(process, &start_time, &not_use, &not_use, &not_use);
            CloseHandle(process);
        }
    }

private:
    DWORD id;               // 进程id
    std::wstring name;      // 进程名称
    std::wstring cmd_line;  // 命令行
    FILETIME start_time;    // 进程启动时间
};
